"""
通用工具函数和响应处理
"""
from functools import wraps
from flask import jsonify
from flask_jwt_extended import verify_jwt_in_request, get_jwt_identity


class ApiResponse:
    """统一API响应格式"""
    
    @staticmethod
    def success(data=None, msg='success', code=200):
        """成功响应"""
        return jsonify({
            'code': code,
            'data': data,
            'msg': msg
        }), 200
    
    @staticmethod
    def error(msg='error', code=400, data=None):
        """错误响应"""
        return jsonify({
            'code': code,
            'data': data,
            'msg': msg
        }), code
    
    @staticmethod
    def paginated(items, total, page, page_size):
        """分页响应"""
        return {
            'list': items,
            'total': total,
            'page': page,
            'pageSize': page_size,
            'pages': (total + page_size - 1) // page_size
        }


def jwt_required_custom(fn):
    """自定义JWT验证装饰器"""
    @wraps(fn)
    def wrapper(*args, **kwargs):
        try:
            verify_jwt_in_request()
            current_user = get_jwt_identity()
            return fn(current_user, *args, **kwargs)
        except Exception as e:
            return ApiResponse.error(msg='Unauthorized', code=401)
    return wrapper
